package com.adnaan.admin.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.adnaan.admin.model.entity.SysMenu;
import com.adnaan.admin.service.SysMenuService;
import com.adnaan.common.model.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 系统菜单管理控制器
 */
@Tag(name = "系统菜单管理", description = "系统菜单管理接口")
@RestController
@RequestMapping("/admin/system/menu")
@RequiredArgsConstructor
public class SysMenuController {

    private final SysMenuService sysMenuService;

    /**
     * 查询菜单列表
     */
    @Operation(summary = "查询菜单列表", description = "查询系统菜单列表")
    @SaCheckPermission("system:menu:list")
    @GetMapping("/list")
    public Result<List<SysMenu>> list(
            @RequestParam(value = "menuName", required = false) String menuName,
            @RequestParam(value = "status", required = false) Integer status) {

        // 构建查询条件
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(menuName), SysMenu::getMenuName, menuName)
                .eq(status != null, SysMenu::getStatus, status)
                .orderByAsc(SysMenu::getParentId)
                .orderByAsc(SysMenu::getSort);

        // 查询菜单列表
        List<SysMenu> menuList = sysMenuService.list(queryWrapper);

        return Result.success(menuList);
    }

    /**
     * 获取菜单详情
     */
    @Operation(summary = "获取菜单详情", description = "根据菜单ID获取菜单详情")
    @SaCheckPermission("system:menu:query")
    @GetMapping("/{id}")
    public Result<SysMenu> getInfo(@PathVariable Long id) {
        SysMenu menu = sysMenuService.getById(id);
        if (menu == null) {
            return Result.error("菜单不存在");
        }
        return Result.success(menu);
    }

    /**
     * 添加菜单
     */
    @Operation(summary = "添加菜单", description = "添加系统菜单")
    @SaCheckPermission("system:menu:add")
    @PostMapping
    public Result<Void> add(@RequestBody SysMenu menu) {
        // 保存菜单
        sysMenuService.save(menu);
        return Result.success();
    }

    /**
     * 修改菜单
     */
    @Operation(summary = "修改菜单", description = "修改系统菜单")
    @SaCheckPermission("system:menu:edit")
    @PutMapping
    public Result<Void> update(@RequestBody SysMenu menu) {
        // 校验菜单是否存在
        SysMenu existMenu = sysMenuService.getById(menu.getId());
        if (existMenu == null) {
            return Result.error("菜单不存在");
        }

        // 不能将菜单设置为自己的子菜单
        if (menu.getId().equals(menu.getParentId())) {
            return Result.error("不能将菜单设置为自己的子菜单");
        }

        // 更新菜单
        sysMenuService.updateById(menu);

        return Result.success();
    }

    /**
     * 删除菜单
     */
    @Operation(summary = "删除菜单", description = "删除系统菜单")
    @SaCheckPermission("system:menu:remove")
    @DeleteMapping("/{id}")
    public Result<Void> remove(@PathVariable Long id) {
        // 校验是否有子菜单
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysMenu::getParentId, id);
        if (sysMenuService.count(queryWrapper) > 0) {
            return Result.error("存在子菜单，不能删除");
        }

        // 删除菜单
        sysMenuService.removeById(id);

        return Result.success();
    }

    /**
     * 获取菜单树形列表
     */
    @Operation(summary = "获取菜单树形列表", description = "获取菜单树形列表，用于角色授权")
    @SaCheckPermission("system:menu:list")
    @GetMapping("/treeselect")
    public Result<List<SysMenu>> treeselect() {
        List<SysMenu> menuTree = sysMenuService.buildMenuSelectTree();
        return Result.success(menuTree);
    }

    /**
     * 获取角色菜单ID列表
     */
    @Operation(summary = "获取角色菜单ID列表", description = "获取角色已分配的菜单ID列表")
    @SaCheckPermission("system:menu:query")
    @GetMapping("/roleMenuIds/{roleId}")
    public Result<List<Long>> getRoleMenuIds(@PathVariable Long roleId) {
        List<Long> menuIds = sysMenuService.selectMenuIdsByRoleId(roleId);
        return Result.success(menuIds);
    }

    /**
     * 获取路由菜单树
     */
    @Operation(summary = "获取路由菜单树", description = "获取当前用户的路由菜单树")
    @GetMapping("/routes")
    public Result<List<SysMenu>> getRoutes() {
        Long userId = cn.dev33.satoken.stp.StpUtil.getLoginIdAsLong();
        List<SysMenu> menuTree = sysMenuService.buildMenuTree(userId);
        return Result.success(menuTree);
    }
} 